package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.zip.Inflater;

import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.os.Build;
import android.print.PageRange;
/*
기능 : 포스트를 띄우는 기능
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class PostListActivity extends BaseActivity implements View.OnClickListener{ // 게시물 목록을 받아오는 Activity

	Location location;
	Geocoder coder;
	
	Intent mIntent;
    String userID;
    String locationID;
    String locationName;
    String groupID;
   
    int i;
    LinearLayout linLayout;
    LinearLayout LL=null;
    int[] imgResource;
   
    int j=0;;
    int curIndexNum;
   
    ArrayList<String> titleArray;
    ArrayList<String> baseArray;
    ArrayList<Bitmap> bitmapArray;
    ArrayList<String> boardIDArray;
    ArrayList<String> latArray;
    ArrayList<String> lonArray;
    ArrayList<LinearLayout> rootView;
   
    LinearLayout indexView;
    ImageView indexCurImg;
    ImageView indexImg;
   
    private ViewFlipper mViewPager;
    float xAtDown, xAtUp;
    String lati, longi;
    
    int curPostNum, wholePostNum;
    private ProgressDialog waitDialog;
    LinearLayout.LayoutParams rLParams;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_post_list);
      
      userID = getIntent().getExtras().getString("userID");
      locationID = getIntent().getExtras().getString("locationID");
      groupID = getIntent().getExtras().getString("groupID");
      
      titleArray = new ArrayList<String>();
      baseArray = new ArrayList<String>();
      boardIDArray = new ArrayList<String>();
      latArray = new ArrayList<String>();
      lonArray = new ArrayList<String>();
      rootView =  new ArrayList<LinearLayout>();

      imgResource = new int[4];
      imgResource[0] = R.drawable.groovepaper_background;
      imgResource[1] = R.drawable.struckaxiom_background;
      imgResource[2] = R.drawable.linedpaper_background;
      imgResource[3] = R.drawable.crossword_background;
      
      mViewPager = (ViewFlipper) findViewById(R.id.postPager);
      
      indexView = (LinearLayout) findViewById(R.id.indexView);
      indexCurImg = new ImageView(getApplicationContext());
      indexCurImg.setImageResource(R.drawable.index_cur_img);
      indexImg = new ImageView(getApplicationContext());
      indexImg.setImageResource(R.drawable.index_img);

      LayoutParams indexParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      indexParams.setMargins(0, 0, 2, 0);
      indexImg.setLayoutParams(indexParams);
      indexCurImg.setLayoutParams(indexParams);
      
      rLParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
      getActionBar().setDisplayShowHomeEnabled(false);
      getActionBar().setDisplayHomeAsUpEnabled(true);
      
      
      if(locationID.equals("0")){
    	  readmyPostAsync readPostmylsit = new readmyPostAsync();
    	  readPostmylsit.execute();
      } else {
    	  readPostListAsync readPostList = new readPostListAsync();
    	  readPostList.execute();
    	  getLocationAsync getLocation = new getLocationAsync();
    	  getLocation.execute();
      }
      
   }
   
   @Override
public boolean onOptionsItemSelected(MenuItem item) {
	// TODO Auto-generated method stub
	   switch(item.getItemId()){
       case android.R.id.home:
           onBackPressed();
           break;
       default: 
        	   return false;
        	   }
	   return true;
}
   
   @Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}

   @Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
	   if(event.getAction() == MotionEvent.ACTION_DOWN) {
		   xAtDown = event.getX();
	   } else if(event.getAction() == MotionEvent.ACTION_UP) {
		   xAtUp = event.getX();   // 터치 끝난지점 x좌표 저장 	
		               if( xAtUp < xAtDown ) {
		                   // 왼쪽 방향 에니메이션 지정
		                   mViewPager.setInAnimation(AnimationUtils.loadAnimation(this,
		                           R.anim.push_left_in));
		                   mViewPager.setOutAnimation(AnimationUtils.loadAnimation(this,
		                           R.anim.push_left_out));
		                            
		                   // 다음 view 보여줌
		                   mViewPager.showNext();
		                   curIndexNum = mViewPager.getDisplayedChild();
//		                   indexView.removeAllViews();
		                   for(int k=0;k<mViewPager.getChildCount();k++){
		                	   if(k==curIndexNum)
		                	   {
		                		   ImageView v = (ImageView)indexView.getChildAt(k);
		                		   v.setImageResource(R.drawable.index_cur_img);
		                	   }
		                	   else{
		        	    		   ImageView v = (ImageView)indexView.getChildAt(k);
		        	    		   v.setImageResource(R.drawable.index_img);
		        	    	   }
		                   }
		               }
		               else if (xAtUp > xAtDown){
		                   // 오른쪽 방향 에니메이션 지정
		            	   mViewPager.setInAnimation(AnimationUtils.loadAnimation(this,
		                           R.anim.push_right_in));
		            	   mViewPager.setOutAnimation(AnimationUtils.loadAnimation(this,
		                           R.anim.push_right_out));
		                   // 전 view 보여줌
		            	   mViewPager.showPrevious();
		            	   curIndexNum = mViewPager.getDisplayedChild();
//		            	   indexView.removeAllViews();
		            	   for(int k=0;k<mViewPager.getChildCount();k++){
		                	   if(k==curIndexNum)
		                	   {
		                		   ImageView v = (ImageView)indexView.getChildAt(k);
		                		   v.setImageResource(R.drawable.index_cur_img);
		                	   }
		        	    	   else{
		        	    		   ImageView v = (ImageView)indexView.getChildAt(k);
		        	    		   v.setImageResource(R.drawable.index_img);
		        	    	   }
		                   }
		               }

	   }
	   return true;
	}
   
   
   protected String[] read_post_list(Context context){
      String pString = null;
      HttpURLConnection conn = null;
      BufferedReader br = null;
      
      String[] result = new String[2];
      result[0] = "error"; //JSON flag
      result[1] = null; //message
      
      try{
          StringBuilder builder = new StringBuilder();
          
          URL url = new URL("http://54.199.194.197/read_board_list.php");
          conn = (HttpURLConnection)url.openConnection();
          
          if(conn != null){
             conn.setConnectTimeout(1000000);   //5�뜝�룞�삕�뜝�떇�슱�삕 而ㅵ뜝�룞�삕�듃 �뜝�룞�삕�뜝�룞�삕.
             conn.setReadTimeout(1000000);
             conn.setDefaultUseCaches(false); //罹먨뜝�떆�궪�삕�뜝�룞�삕�뜝�룞�삕
             conn.setDoInput(true); // �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 �뜝�떩源띿삕 �뜝�룞�삕�뜝占� �뜝�룞�삕�뜝�룞�삕
             conn.setDoOutput(true); // �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝占� �뜝�룞�삕�뜝�룞�삕 
             conn.setRequestMethod("POST"); // �뜝�룞�삕�뜝占� �뜝�룞�삕�뜝�룞�삕�뜝占� POST
             conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); // �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 <Form>�뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕 �뜝�떬�뼲�삕�뜝占� �뜝�떢怨ㅼ삕 �뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕�뜝占� 泥섇뜝�룞�삕�뜝�떦�씛�삕�뜝占� �뜝�룞�삕 �뜝�떙琉꾩삕�뜝�뙏�뙋�삕
              
            StringBuffer buffer = new StringBuffer();
            buffer.append("user_id").append("=").append(userID).append("&");
            buffer.append("location_id").append("=").append(locationID).append("&");
            buffer.append("group_id").append("=").append(groupID);
            
            //�뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕�뜝�룞�삕閭먨뜝占�	
            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
           // �뜝�룞�삕�뜝�룞�삕�뜝�룞�삕�뜝�룞�삕 �뜝�룞�삕��茹녑뜝占�
           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
              String line;
              while((line = br.readLine()) != null){
                 builder.append(line);
              }
              
              br.close();
              
              pString =  builder.toString();
              
              JSONObject jObject = new JSONObject(pString);
              JSONArray titleObject = new JSONArray(jObject.getString("title"));
              JSONArray bIDObject = new JSONArray(jObject.getString("board_id"));
              JSONArray baseObject = new JSONArray(jObject.getString("base"));
              
              for(int i=0;i<titleObject.length();i++) {
                 titleArray.add(titleObject.getString(i));
                 boardIDArray.add(bIDObject.getString(i));
                 baseArray.add(baseObject.getString(i));
              }
              
              
          }else{
             
             throw new Exception("network error");
          }
          
       }catch(SocketTimeoutException se){
          
          result[1] = "network error";
          
       }catch(Exception e){
          
          result[1] = e.getMessage();
          
       }finally{
          
          if(conn != null)
             conn.disconnect();

          if(br != null){
             try {
                br.close();
            } catch (Exception e2) {
               // TODO: handle exception
               result[1] = e2.getMessage();
            }
          }
       }
       return result;
   }
   
   protected String[] read_my_post_list(Context context){
	   String pString = null;
	      HttpURLConnection conn = null;
	      BufferedReader br = null;
	      
	      String[] result = new String[2];
	      result[0] = "error"; //JSON flag
	      result[1] = null; //message
	      
	      try{
	          StringBuilder builder = new StringBuilder();
	          
	          URL url = new URL("http://54.199.194.197/read_board_my_list.php");
	          conn = (HttpURLConnection)url.openConnection();
	          
	          if(conn != null){
	             conn.setConnectTimeout(500000000);   
	             conn.setReadTimeout(5000000-0);
	             conn.setDefaultUseCaches(false); 
	             conn.setDoInput(true); 
	             conn.setDoOutput(true); 
	             conn.setRequestMethod("POST"); 
	             conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
	            StringBuffer buffer = new StringBuffer();
	            buffer.append("user_id").append("=").append(userID);

	            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	            PrintWriter writer = new PrintWriter(outStream);
	            writer.write(buffer.toString());
	            writer.flush();
	            
	           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
	           br = new BufferedReader(inputStream);
	              
	              String line;
	              while((line = br.readLine()) != null){
	                 builder.append(line);
	              }
	              
	              br.close();
	              
	              pString =  builder.toString();
	              
	              JSONObject jObject = new JSONObject(pString);
	              JSONArray titleObject = new JSONArray(jObject.getString("title"));
	              JSONArray bIDObject = new JSONArray(jObject.getString("board_id"));
	              JSONArray baseObject = new JSONArray(jObject.getString("base"));
	              
	              for(int i=0;i<titleObject.length();i++) {
	                 titleArray.add(titleObject.getString(i));
	                 boardIDArray.add(bIDObject.getString(i));
	                 baseArray.add(baseObject.getString(i));
	              }
	              
	              
	          }else{
	             
	             throw new Exception("network error");
	          }
	          
	       }catch(SocketTimeoutException se){
	          
	          result[1] = "network error";
	          
	       }catch(Exception e){
	          
	          result[1] = e.getMessage();
	          
	       }finally{
	          
	          if(conn != null)
	             conn.disconnect();

	          if(br != null){
	             try {
	                br.close();
	            } catch (Exception e2) {
	               // TODO: handle exception
	               result[1] = e2.getMessage();
	            }
	          }
	       }
	       return result;
	   }
   
   public class readPostListAsync extends AsyncTask<String, String, String> {
      @Override
      protected void onPreExecute() {
    	  waitDialog = new ProgressDialog(PostListActivity.this, R.style.MyProgressTheme);
			waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			waitDialog.setMessage("게시물 목록을 로딩중입니다...");
			waitDialog.setIcon(R.id.icon);
			waitDialog.setIndeterminate(true);
			waitDialog.setCancelable(true);
			waitDialog.show();
         super.onPreExecute();
      }
      @Override
      protected String doInBackground(String... params) {
    	 read_post_list(PostListActivity.this);
         return null;
      }
      @Override
      protected void onPostExecute(String result) {
			makeBitmap();
			wholePostNum = titleArray.size();
			curPostNum = 0;
			makelist();
			waitDialog.dismiss();
    	  
         super.onPostExecute(result);
      }
      @Override
      protected void onCancelled() {
         super.onCancelled();
      }
   }
   
   public class readmyPostAsync extends AsyncTask<String, String, String> {
	   @Override
	protected void onPreExecute() {
		   waitDialog = new ProgressDialog(PostListActivity.this, R.style.MyProgressTheme);
			waitDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			waitDialog.setMessage("게시물 목록을 로딩중입니다...");
			waitDialog.setIcon(R.id.icon);
			waitDialog.setIndeterminate(true);
			waitDialog.setCancelable(true);
			waitDialog.show();
		super.onPreExecute();
	}
	   @Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		 read_my_post_list(PostListActivity.this);
		return null;
	}
	   @Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
			makeBitmap();
			wholePostNum = titleArray.size();
			curPostNum = 0;
			makelist();
			waitDialog.dismiss();
	         super.onPostExecute(result);
	      }
	      @Override
	      protected void onCancelled() {
	         super.onCancelled();
	      }
   }
   
   public class getLocationAsync extends AsyncTask<String, String, String> {
	   @Override
	protected void onPreExecute() {
		// TODO Auto-generated method stub
		super.onPreExecute();
	}
	   @Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub
		   get_location(PostListActivity.this);
		   return null;
	}
	   @Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		   locationName = "";
		   coder = new Geocoder(PostListActivity.this, Locale.KOREA);
		   List<Address> addresses;
		   Double dLati, dLong;
		   dLati = Double.parseDouble(latArray.get(0));
		   dLong = Double.parseDouble(lonArray.get(0));
		try {
			addresses = coder.getFromLocation(dLati, dLong, 1);
			if(addresses != null) {
				Address addr = addresses.get(0);
				for(int i=0;i<=addr.getMaxAddressLineIndex();i++) {
					String addLine = addr.getAddressLine(i);
					locationName += String.format("%s", addLine);
				}
			} else {
				locationName = "위치 를 찾을 수 없음";
			}
			
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		getActionBar().setTitle(locationName);
	}  
   }
   
   protected void get_location(Context context){
	   String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		try{
	  	StringBuilder builder = new StringBuilder();
	  	
	  	URL url = new URL("http://54.199.194.197/get_location_name.php");
	  	conn = (HttpURLConnection)url.openConnection();
	  	
	  	if(conn != null){
	  		conn.setConnectTimeout(150000);		  		
	  		conn.setReadTimeout(150000);
	  		conn.setDefaultUseCaches(false);
	      	conn.setDoInput(true); 	      	
	      	conn.setDoOutput(true); 	      	
	      	conn.setRequestMethod("POST"); 	      	
	      	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded"); 	         
	    	StringBuffer buffer = new StringBuffer();
	    	buffer.append("location_id").append("=").append(locationID);

	       OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
	       PrintWriter writer = new PrintWriter(outStream);
	       writer.write(buffer.toString());
	       writer.flush();

           InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
           br = new BufferedReader(inputStream);
              
              String line;
              while((line = br.readLine()) != null){
                 builder.append(line);
              }
              
              br.close();
              
              pString =  builder.toString();
              
              JSONObject jObject = new JSONObject(pString);
              JSONArray latObject = new JSONArray(jObject.getString("lat"));
              JSONArray longObject = new JSONArray(jObject.getString("long"));
              
       
             latArray.add(latObject.getString(0));
             lonArray.add(longObject.getString(0));
             
             
	      
	  	}else{
	  		
	  		throw new Exception("network error");
	  	}
	  	
	  }catch(SocketTimeoutException se){
	  	
	  	
	  }catch(Exception e){
	  	
	  	
	  }finally{
	  	
	  	if(conn != null)
	  		conn.disconnect();

	  	if(br != null){
	  		try {
	  			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
	  	}
	  }
   }
   
   public void makeBitmap() {
      bitmapArray = new ArrayList<Bitmap>();   
      for(int i=0;i<baseArray.size();i++){
            byte[] decodeByte = Base64.decode(baseArray.get(i), Base64.NO_WRAP);
            Bitmap decodeBitmap = BitmapFactory.decodeByteArray(decodeByte, 0, decodeByte.length);
            bitmapArray.add(decodeBitmap);
      }
   }
   
	   public void makelist() {
	        Display display = getWindowManager().getDefaultDisplay();
	        Typeface mTypeface = Typeface.createFromAsset(this.getAssets(), "fonts/whitechok.ttf");
	        int count = 0;
	        int arrayNum = 0;
	        for(int s=0; s<(titleArray.size()/4+1);s++) {
	        	rootView.add(new LinearLayout(PostListActivity.this));
	        	rootView.get(s).setLayoutParams(rLParams);
	        	rootView.get(s).setOrientation(LinearLayout.VERTICAL);
	        }
	        for(int k=0; k<titleArray.size(); k++){
	           if(count==4){
	              mViewPager.addView(rootView.get(arrayNum));
	              arrayNum++;
	              count=0;
	           }
	           LL = new LinearLayout(PostListActivity.this);
	           LL.setBackgroundResource(imgResource[k%4]);
	           LL.setOrientation(LinearLayout.HORIZONTAL);
	           LL.setTag(k);
	           
	           LayoutParams LLParams = new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, display.getHeight()/5);
	           LLParams.setMargins(15, 10, 15, 10);
	           LL.setGravity(Gravity.CENTER);
	           LL.setLayoutParams(LLParams);
	           LL.setPadding(10, 5, 10, 5);
	           LL.setWeightSum(3);
	           
	           LayoutParams TVParams = new LayoutParams(0, LayoutParams.MATCH_PARENT,1);
	           LayoutParams IVParams = new LayoutParams(0, display.getHeight()/5,2);

	          
	           ImageView iv = new ImageView(PostListActivity.this);
	           iv.setImageBitmap(bitmapArray.get(k));
	           IVParams.gravity=Gravity.CENTER;
	           iv.setLayoutParams(IVParams);
	           LL.addView(iv);
	          
	           TextView tv = new TextView(PostListActivity.this);
	           tv.setGravity(Gravity.CENTER);
	           tv.setText(titleArray.get(k));
	           tv.setTextColor(Color.parseColor("#ff6e57"));
	           tv.setTypeface(mTypeface);
	           tv.setLayoutParams(TVParams);
	           LL.addView(tv);
	           
	           LL.setOnClickListener(new View.OnClickListener() {
	                
	              @Override
	                public void onClick(View v) {
	                   // TODO Auto-generated method stub
	                   
	                   String board_id = boardIDArray.get((Integer)v.getTag());
	                   Intent mIntent = new Intent(PostListActivity.this, ReadPostActivity.class);
	                    mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	                    mIntent.putExtra("board_id", board_id);
	                    mIntent.putExtra("userID", userID);
	                    startActivity(mIntent);
	                }
	             });
	           rootView.get(arrayNum).addView(LL);
	           count++;
	        }
	        mViewPager.addView(rootView.get(arrayNum));
	        bitmapArray.clear();
	        rootView.clear();
	        for(int k=0;k<=((titleArray.size()-1)/4);k++) {
	             if(k==0)
	                indexView.addView(indexCurImg, k);
	             else {
	            	 indexImg = new ImageView(getApplicationContext());
	            	 indexImg.setImageResource(R.drawable.index_img);
	            	 LayoutParams indexParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
	            	 indexParams.setMargins(0, 0, 2, 0);
	            	 indexImg.setLayoutParams(indexParams);
	            	 indexView.addView(indexImg, k);
	             }
	       }
	   }
   
   public class makeListAsync extends AsyncTask<String, String, String> {
	   @Override
	protected void onPreExecute() {
		super.onPreExecute();
	}
	   @Override
	protected String doInBackground(String... params) {
		return null;
	}
	protected void onPostExecute(String result) {
		   if(curPostNum<wholePostNum)
			   makeBitmap();
		   curPostNum +=4;
	   };
   }
}
